package com.liveinstars.quhui.application.service;


import com.liveinstars.api.dto.*;
import com.liveinstars.api.post.dto.PostDetailDto;
import com.liveinstars.api.post.facade.IPostsApi;
import com.liveinstars.api.query.InterestQuery;
import com.liveinstars.quhui.business.interest.service.InterestDomainService;
import com.onepiece.shipelves.common.utils.ServiceUtils;
import com.onepiece.shipelves.common.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class InterestApplicationService {
    @Autowired
    InterestDomainService interestService;

    @Autowired
    IPostsApi postsApi;


    public List<InterestSimpleDto> getInterests() {

        List<InterestSimpleDto> allInterest = interestService.getAllInterest();
        List<Integer> ids = ServiceUtils.fetchPropertyList(allInterest, InterestSimpleDto::getId);
        if(ids.size() > 0){
            Map<Integer, List<PostDetailDto>> map = postsApi.listByInterestHotPost(ids);
            setHotPost(allInterest, map);
        }
        return allInterest;
    }

    public Page<InterestDto> pageByQuery(InterestQuery query) {
        return interestService.pageByQuery(query);
    }

    public List<InterestDto> getMyInterests(Integer userId) {
        List<InterestDto> myInterests = interestService.getMyInterests(userId);
        List<Integer> ids = ServiceUtils.fetchPropertyList(myInterests, InterestDto::getId);
        if(ids.size() > 0){
            Map<Integer, List<PostDetailDto>> map = postsApi.listByInterestHotPost(ids);
            setHotPost(myInterests, map);
        }

        return myInterests;
    }

    private <T extends InterestSimpleDto> void setHotPost(List<T> myInterests, Map<Integer, List<PostDetailDto>> map) {
        myInterests.stream().forEach(interest -> {
            interest.setRecentPost(Optional.ofNullable(map.get(interest.getId()))
                    .orElseGet(LinkedList::new)
                    .stream()
                    .filter(Objects::nonNull)
                    .map(post -> new RecentPost(post.getId(), post.getTitle()))
                    .collect(Collectors.toList()));
        });
    }



    public List<InterestSimpleDto> getMyInterestsSimple(Integer userId) {
        List<InterestSimpleDto> myInterests = interestService.getMyInterestsSimple(userId);
        List<Integer> ids = ServiceUtils.fetchPropertyList(myInterests, InterestSimpleDto::getId);
        if(ids.size() > 0){
            Map<Integer, List<PostDetailDto>> map = postsApi.listByInterestHotPost(ids);
            setHotPost(myInterests, map);
        }
        return myInterests;
    }

    public InterestDetailDto getDetailById(Integer id) {
        return interestService.getDetailById(id);
    }

    public Boolean joinInterest(JoinInterest interest, Integer userId) {
        return interestService.joinInterest(interest, userId);
    }
}
